package de.tum.icuproject.persistence.couchdb;

import java.io.IOException;
import java.util.Scanner;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import de.tum.icuproject.Subscriber;

/**
 * Handles http requests
 * @author stefanoturchetta
 *
 */
public abstract class RequestHandler extends AsyncTask<String, Void, String> {

	protected static String DB_URL = "http://icuproject.iriscouch.com/";

	private Subscriber subscriber;

	public RequestHandler(Subscriber subscriber) {
		this.subscriber = subscriber;
	}

	private String readResponse(HttpResponse response) throws IllegalStateException, IOException {
		Scanner scanner = new Scanner(response.getEntity().getContent());
		String result = "";
		while (scanner.hasNextLine()) {
			result += scanner.nextLine();
		}
		scanner.close();
		return result;
	}

	protected String doGet(String requestPage) throws ClientProtocolException, IOException {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet request = new HttpGet(requestPage);
		HttpResponse response = httpClient.execute(request);
		return this.readResponse(response);
	}

	protected String doPost(String requestPage, String jsonString) throws ClientProtocolException, IOException {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost request = new HttpPost(requestPage);
		request.addHeader("Content-Type", "application/json");
		request.addHeader("Accept", "application/json");
		request.setEntity(new StringEntity(jsonString));
		HttpResponse response = httpClient.execute(request);
		return this.readResponse(response);
	}

	protected String doPut(String requestPage) throws ClientProtocolException, IOException {
		return this.doPut(requestPage, null);
	}

	protected String doPut(String requestPage, String jsonString) throws ClientProtocolException, IOException {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPut request = new HttpPut(requestPage);
		request.addHeader("Content-Type", "application/json");
		request.addHeader("Accept", "application/json");
		if (jsonString != null) {
			request.setEntity(new StringEntity(jsonString)); 
		}
		HttpResponse response = httpClient.execute(request);
		return this.readResponse(response);
	}

	protected String doDelete(String requestPage) throws ClientProtocolException, IOException {
		HttpClient httpClient = new DefaultHttpClient();
		HttpDelete request = new HttpDelete(requestPage);
		HttpResponse response = httpClient.execute(request);
		return this.readResponse(response);
	}

	protected Subscriber getSubscriber() {
		return subscriber;
	}

}
